Java final 与 C++ const
全部标签 我在看一个成员函数intfunct(intx)const;我想知道是否staticintfunct(intx);会更好。如果一个成员函数不使用任何成员变量,它应该是静态的吗?有什么事情会阻止这一点吗? 最佳答案 假设这是C++,声明为const的函数表示它不打算更改调用它的实例上的数据成员,即this指针。既然有办法规避这一点,这不是保证,只是声明。静态函数不对特定实例进行操作,因此不使用“this”指针。因此,它是一种非常幼稚的“const”。如果您的方法不需要绑定(bind)到特定实例,则将其设为静态是有意义的。但是,如果您的方
这个问题在这里已经有了答案:Deletingelementsfromstd::setwhileiterating(8个回答)关闭3年前。有人可以帮我吗?编译这段代码:voidtest(){std::settest;test.insert(42);test.erase(std::remove(test.begin(),test.end(),30),test.end());//编译时出现如下错误:$makeg++-c-Wall-pedantic-errors-Wextra-Wunused-Werrora_star.cpp/usr/lib/gcc/i686-pc-cygwin/4.3.4/i
这个问题在这里已经有了答案:Deletingelementsfromstd::setwhileiterating(8个回答)关闭3年前。有人可以帮我吗?编译这段代码:voidtest(){std::settest;test.insert(42);test.erase(std::remove(test.begin(),test.end(),30),test.end());//编译时出现如下错误:$makeg++-c-Wall-pedantic-errors-Wextra-Wunused-Werrora_star.cpp/usr/lib/gcc/i686-pc-cygwin/4.3.4/i
我正在修复一些代码中的另一个错误,并遇到了一些我认为是错误的代码;但是,此代码在gcc4.4、4.5和4.6下编译,并且似乎按“预期”运行。谁能告诉我这是否是有效的c++?structfoo{intbar;};foomyfunction(fooconst&orig){foofooOnStack=orig;fooOnStack.bar*=100;returnfooOnStack;}voidmyOtherFunction(fooconst&orig){fooconst&retFoo=myfunction();//perhapsdosometestsonretFoo.bar...}如果这是有
我正在修复一些代码中的另一个错误,并遇到了一些我认为是错误的代码;但是,此代码在gcc4.4、4.5和4.6下编译,并且似乎按“预期”运行。谁能告诉我这是否是有效的c++?structfoo{intbar;};foomyfunction(fooconst&orig){foofooOnStack=orig;fooOnStack.bar*=100;returnfooOnStack;}voidmyOtherFunction(fooconst&orig){fooconst&retFoo=myfunction();//perhapsdosometestsonretFoo.bar...}如果这是有
假设我有以下功能:conststd::string&Cat::getKittenName()const{Kitten*kitty=getKitty();returnkitty->getName();}Kitten::getName返回conststd::string&我如何最好地处理kitty是的情况空指针?我可以返回std::string("")但随后我返回对临时且实际上保证未定义行为的引用。我可以更改getKittenName函数以返回一个std::string来解决这个问题,但是我会为kitty可用。现在我觉得最好的选择是:conststd::string&Cat::getKit
假设我有以下功能:conststd::string&Cat::getKittenName()const{Kitten*kitty=getKitty();returnkitty->getName();}Kitten::getName返回conststd::string&我如何最好地处理kitty是的情况空指针?我可以返回std::string("")但随后我返回对临时且实际上保证未定义行为的引用。我可以更改getKittenName函数以返回一个std::string来解决这个问题,但是我会为kitty可用。现在我觉得最好的选择是:conststd::string&Cat::getKit
在relatedquestion中,据说没有指向非成员const函数的指针。另外,C++118.3.5/6说Theeffectofacv-qualifier-seqinafunctiondeclaratorisnotthesameasaddingcv-qualificationontopofthefunctiontype.Inthelattercase,thecv-qualifiersareignored.[Note:afunctiontypethathasacv-qualifier-seqisnotacv-qualifiedtype;therearenocv-qualifiedfun
在relatedquestion中,据说没有指向非成员const函数的指针。另外,C++118.3.5/6说Theeffectofacv-qualifier-seqinafunctiondeclaratorisnotthesameasaddingcv-qualificationontopofthefunctiontype.Inthelattercase,thecv-qualifiersareignored.[Note:afunctiontypethathasacv-qualifier-seqisnotacv-qualifiedtype;therearenocv-qualifiedfun
我一直被教导非原始类型应该通过const引用而不是在可能的情况下通过值传递,即:voidfoo(std::stringstr);//badvoidfoo(conststd::string&str);//good但我今天在想,也许实际上一些简单的用户定义类型实际上可能更好地按值传递,例如:classVector2{public:floatx,y;...constructors,operatorsoverloads,utilitymethods,etc...};voidfoo(Vector2pos);voidfoo(constVector2&pos);//isthisreallybette